import { useEffect, useRef, useState } from 'react';
 
const ScrollToTopButton = ({ threshold }) => {
  const [showButton, setShowButton] = useState(false);
  const scrollRef = useRef(null);
 
  const checkScrollTop = () => {
    if (!scrollRef.current) return;
    setShowButton(scrollRef.current.scrollTop >= threshold);
  };
 
  const handleScroll = () => {
    if (scrollRef && scrollRef.current) {
      checkScrollTop();
    }
  };
 
  useEffect(() => {
    document.addEventListener('scroll', handleScroll, { passive: true });
    return () => {
      document.removeEventListener('scroll', handleScroll);
    };
  }, []);
 
  const scrollToTop = () => {
    if (scrollRef.current) {
      scrollRef.current.scrollTo({
        top: 0,
        behavior: 'smooth',
      });
    }
  };
 
  return (
    <button
      style={{ display: showButton ? 'inline' : 'none' }}
      onClick={scrollToTop}
    >
      回到顶部
    </button>
  );
};
 
export default ScrollToTopButton;